package com.sky.sd.oauth.config;

import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.core.Authentication;
import org.springframework.security.oauth2.config.annotation.web.configuration.EnableResourceServer;
import org.springframework.security.oauth2.config.annotation.web.configuration.ResourceServerConfigurerAdapter;
import org.springframework.security.oauth2.config.annotation.web.configurers.ResourceServerSecurityConfigurer;
import org.springframework.security.oauth2.provider.authentication.BearerTokenExtractor;
import org.springframework.security.oauth2.provider.authentication.TokenExtractor;
import org.springframework.security.web.util.matcher.RequestMatcher;
import org.springframework.web.context.request.ServletWebRequest;

import javax.servlet.http.HttpServletRequest;

/**
 * <br/>功能:
 * <br/>版本: 1.0
 * <br/>开发人员: 弓振
 * <br/>创建日期: 2020/3/9 13:45
 * <br/>修改日期: 2020/3/9 13:45
 * <br/>修改列表:
 */
@Configuration
@EnableResourceServer
public class ResourceServerConfig extends ResourceServerConfigurerAdapter {

    @Override
    public void configure(HttpSecurity http) throws Exception {
        http.httpBasic()
                .and()
            .exceptionHandling().authenticationEntryPoint(
                (request, response, authException)-> {
                    response.sendError(401,"kkk");
//                    RestResponseProcessor.print401(new ServletWebRequest(request, response), authException);
                }).accessDeniedHandler((request, response, accessDeniedException)->{
                    response.sendError(403,"kkk");
//                    RestResponseProcessor.print403(new ServletWebRequest(request, response), accessDeniedException);
                })
                .and()
            .requestMatcher(new OauthRequestMatcher()).authorizeRequests().anyRequest().authenticated();
    }

    @Override
    public void configure(ResourceServerSecurityConfigurer resources) throws Exception {
        resources.authenticationEntryPoint( (request, response, authException)->{
            response.sendError(401,"kkk");
//            RestResponseProcessor.print401(new ServletWebRequest(request, response), authException);
        });
    }

    private class OauthRequestMatcher implements RequestMatcher {

        TokenExtractor tokenExtractor = new BearerTokenExtractor();

        @Override
        public boolean matches(HttpServletRequest request) {
            Authentication authentication = tokenExtractor.extract(request);
            return authentication != null;
        }
    }
}
